package com.greencloud.util;

import com.greencloud.bean.GetPath;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;

import java.io.*;
import java.util.Date;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtil {
    /*
            模板读取
     */
    public static void generate(Template template, VelocityContext ctx, String sourceFilePath) throws IOException {
        PrintWriter writer = null;
        try {
            File file = new File(sourceFilePath);
            File tmp = new File(file.getParent());
            if (!tmp.exists()) {
                tmp.mkdirs();
            }
            writer = new PrintWriter(sourceFilePath);
            template.merge(ctx, writer);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            writer.close();
        }
    }
    /*
            删除文件
     */

    public static void delFolder(String folderPath) throws IOException {
        try {
            delAllFile(folderPath); //删除完里面所有内容
            String filePath = folderPath;
            filePath = filePath.toString();
            java.io.File myFilePath = new java.io.File(filePath);
            myFilePath.delete(); //删除空文件夹
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*删除指定文件夹下所有文件
    param path 文件夹完整绝对路径
    */
    public static boolean delAllFile(String path) throws IOException {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
                delFolder(path + "/" + tempList[i]);//再删除空文件夹
                flag = true;
            }
        }
        return flag;
    }

    /*
            压缩下载
     */

    public static void zipDownload() throws IOException {
           GetPath getPath=new GetPath();
            ZipUtils.doCompress(getPath.getProjectPath()+getPath.getJavaPath(), getPath.getZipfile());
    }

}
